package com.example.remoteaction.extension.demo.client;

import java.util.ArrayList;
import java.util.List;

import com.example.remoteaction.extension.demo.domain.School;
import com.google.code.gwt.remoteaction.client.ActionExecutionService;
import com.google.code.gwt.remoteaction.client.ActionExecutionServiceAsync;
import com.google.code.gwt.remoteaction.client.ActionProxy;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Gwt_remote_action_extension_demo implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);

	private List<School> receivedSchoolList = new ArrayList<School>();
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		//--------------------------------------
		// Added to config gwt-remote-action
		ActionExecutionServiceAsync actionExecutionService = (ActionExecutionServiceAsync) GWT.create(ActionExecutionService.class);
		((ActionProxy) greetingService).setActionExecutor(actionExecutionService);
		//--------------------------------------
		
		final Button sendButton = new Button("Get 1 School Info");
		final Button sendButton2 = new Button("Get All Schools Info");
		final Button sendButton3 = new Button("Send received schools objects back to server");
		
		final CheckBox checkBox = new CheckBox();
		checkBox.setText("Fetch Students?");

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		sendButton2.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("nameFieldContainer").add(checkBox);
		RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get("sendButton2Container").add(sendButton2);
		RootPanel.get("sendButton3Container").add(sendButton3);
		
		
		// Focus the cursor on the name field when the app loads
		checkBox.setFocus(true);
		
		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();

			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				receivedSchoolList.clear();
				if(event.getSource() == sendButton){
					getOneSchool();
				}else{
					getAllSchool();
				}
				
				
				
			}

		
			
			private void getOneSchool() {
				
				final Boolean fetchStudent = checkBox.getValue();
				serverResponseLabel.setText("");
				greetingService.getSchool(fetchStudent, new AsyncCallback<School>() {
					
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user
						dialogBox
								.setText("Remote Procedure Call - Failure");
						serverResponseLabel
								.addStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(SERVER_ERROR);
						dialogBox.center();
						closeButton.setFocus(true);
					}

					public void onSuccess(School result) {
						receivedSchoolList.add(result);
						dialogBox.setText("Remote Procedure Call");
						serverResponseLabel
								.removeStyleName("serverResponseLabelError");
						
						serverResponseLabel.setHTML(reportSchool(result, fetchStudent.booleanValue()));
						
						dialogBox.center();
						closeButton.setFocus(true);
					}
				});
				
			}
			
			private void getAllSchool() {
				
				final Boolean fetchStudent = checkBox.getValue();
				serverResponseLabel.setText("");
				greetingService.getAllSchool(fetchStudent, new AsyncCallback<List<School>>() {
					
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user
						dialogBox
								.setText("Remote Procedure Call - Failure");
						serverResponseLabel
								.addStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(SERVER_ERROR);
						dialogBox.center();
						closeButton.setFocus(true);
					}

					public void onSuccess(List<School> result) {
						receivedSchoolList.addAll(result);
						dialogBox.setText("Remote Procedure Call");
						serverResponseLabel
								.removeStyleName("serverResponseLabelError");
						
						String response="";
						for(School s :result){
							response+=reportSchool(s, fetchStudent);
						}
						serverResponseLabel.setHTML(response);
						
						dialogBox.center();
						closeButton.setFocus(true);
					}
				});
				
			}
			private String reportSchool(School school, Boolean fetchStudent){
				if(fetchStudent.booleanValue()){
					
					return "School Name: "+school.getSchoolName() +
							"<br> "+
							"number of students: "+school.getStudentList().size()+"<br>"
							+"student list class:"+ school.getStudentList().getClass()+"<br>";
				}else{
					return "School Name: "+school.getSchoolName() +
							"<br> "+
							"student object: "+ school.getStudentList()+"<br>";
				}
				
				
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		sendButton2.addClickHandler(handler);
		
		sendButton3.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				greetingService.saveSchool(receivedSchoolList, new AsyncCallback<String>() {
					
					@Override
					public void onSuccess(String result) {
						dialogBox.setText("Remote Procedure Call");
						serverResponseLabel
								.removeStyleName("serverResponseLabelError");
						
						
						serverResponseLabel.setHTML(result);
						
						dialogBox.center();
						closeButton.setFocus(true);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						dialogBox.setText("Remote Procedure Call - Failure");
						serverResponseLabel
								.addStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(SERVER_ERROR);
						dialogBox.center();
						closeButton.setFocus(true);
					}
				});
			}
		});
		
	}
}
